package au.edu.utas.yu_qiao_group.luckyman.ui.raffledetail;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import java.io.File;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

public class ImagePickerListener implements View.OnClickListener {
  private final Context mCtx;
  private final Activity mActivity;
  private final Fragment mFragment;
  private File fileDir;

  public static final int REQUEST_PERMISSION_CAMERA_CODE = 123;
  public static final int CAPTURE_PHOTO = 1;
  public static final int CROP_PHOTO = 2;
  public static final int REQUEST_CODE_PICK_IMAGE = 3;
  private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE = 6;
  private static final int MY_PERMISSIONS_REQUEST_CALL_PHONE2 = 7;
  private File temp;
  private String filename;
  private Uri imageUri;

  public ImagePickerListener(Context mCtx, Activity mActivity, Fragment mFragment) {
    this.mCtx = mCtx;
    this.mActivity = mActivity;
    this.mFragment = mFragment;
    fileDir = mCtx.getExternalFilesDir("my_capture");
  }

  @Override
  public void onClick(View v) {
    showChoosePicDialog();
  }

  private void showChoosePicDialog() {
    AlertDialog.Builder builder = new AlertDialog.Builder(mCtx);
    builder.setTitle("Add Logo as Cover");
    String[] items = {"Take Picture", "Choose Album"};
    builder.setNegativeButton("cancel", null);
    builder.setItems(items, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        if (checkPhotoPermission()) {
          switch (which) {
            case 0:
              captureImages();
              break;
            case 1:
              selectAlbum();
              break;
          }
        }
        ;
      }

    });
    builder.show();
  }

  public boolean checkPhotoPermission() {
    boolean result = false;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
      Log.i("VERSION", "system version > 6.0");
      if (ContextCompat.checkSelfPermission(mCtx,
              Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
        Log.i("PEMISSION", "granted to capture image");
        result = true;
      } else {
        Log.i("PEMISSION", "ungranted to capture image, need permission");
        ActivityCompat.requestPermissions(mActivity,
                new String[]{Manifest.permission.CAMERA},
                REQUEST_PERMISSION_CAMERA_CODE);
      }
    } else {
      Log.i("VERSION", "system version < 6.0");
    }
    return result;
  }

  private void captureImages() {
    if (!fileDir.exists()) {
      fileDir.mkdir();
    }
    temp = new File(fileDir, "temp.jpg");
    try {
      if (temp.exists()) {
        temp.delete();
      }
      temp.createNewFile();
    } catch (Exception e) {
      e.printStackTrace();
    }

    imageUri = FileProvider.getUriForFile(mCtx, mCtx.getPackageName() + ".fileprovider", temp);
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
    mFragment.startActivityForResult(intent, CAPTURE_PHOTO);
  }

  void selectAlbum() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    mFragment.startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
  }

  public String onActivityResult(int req, int res, Intent data) {
    switch (req) {
      case CAPTURE_PHOTO:
        if (res == Activity.RESULT_OK) {
          try {
            performCrop(imageUri);
          } catch (Exception e) {
            Toast.makeText(mCtx, "crushed", Toast.LENGTH_SHORT).show();
          }
        } else {
          Log.i("gg", "gg");
        }
        break;
      case REQUEST_CODE_PICK_IMAGE:
        if (res == Activity.RESULT_OK) {
          try {
            Uri uri = data.getData();
            performCrop(uri);
          } catch (Exception e) {
            e.printStackTrace();
            Log.d("tag", e.getMessage());
            Toast.makeText(mCtx, "crushed", Toast.LENGTH_SHORT).show();
          }
        } else {
          Log.i("gg", "gg");
        }
        break;
      case CROP_PHOTO:
        break;
      default:
    }
    return filename;
  }

  private void performCrop(Uri picUri) {
    try {
      filename = System.currentTimeMillis() + ".jpg";
      File output = new File(fileDir, filename);
      if (output.exists()) {
        output.delete();
      }
      output.createNewFile();
      Uri outPutUri = Uri.fromFile(output);
      Intent cropIntent = new Intent("com.android.camera.action.CROP");
      cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
      cropIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
      cropIntent.setDataAndType(picUri, "image/*");
      cropIntent.putExtra("crop", "true");
      cropIntent.putExtra("aspectX", 1);
      cropIntent.putExtra("aspectY", 1);
      cropIntent.putExtra("outputX", 256);
      cropIntent.putExtra("outputY", 256);
      cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outPutUri);
      cropIntent.putExtra("return-data", false);
      mFragment.startActivityForResult(cropIntent, CROP_PHOTO);
    } catch (Exception anfe) {
      //display an error message
      String errorMessage = "Whoops - your device doesn't support the crop action!";
      Toast.makeText(mCtx, errorMessage, Toast.LENGTH_SHORT).show();
    }
  }

  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

    if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE) {
      if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        captureImages();
      } else {
        // Permission Denied
        Toast.makeText(mCtx, "Permission Denied", Toast.LENGTH_SHORT).show();
      }
    }


    if (requestCode == MY_PERMISSIONS_REQUEST_CALL_PHONE2) {
      if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        selectAlbum();
      } else {
        // Permission Denied
        Toast.makeText(mCtx, "Permission Denied", Toast.LENGTH_SHORT).show();
      }
    }
  }
}
